require 'rss/1.0'         
require 'rss/2.0'         
require 'open-uri'

class Info < ActiveRecord::Base
  
  belongs_to :tool
  belongs_to :info_type, :counter_cache => true
  
  validates_presence_of :title
  validates_uniqueness_of :title, :scope => :sm_content
  validates_length_of :email_title, :maximum => 30, :allow_blank => true
  validates_length_of :sm_content, :maximum => 400, :allow_blank => true
  
  def self.all_gifts
    find_all_by_money_purpose('gift')
  end

  def self.send_emails!
    find_all_by_emails_spread_status('ready').each do |info|
      info.emails_spreading!
      logger.debug "准备邮件推广-#{info.title}"
      User.all(:order => 'rand()').each do |user|
        begin
          UserMailer.deliver_send_info info,user
          info.add_emails_count
        rescue Exception => e
          logger.error "发邮件给#{user.email}失败:#{e}"
        end        
        sleep(rand(3))
      end
      info.emails_spread_done!
    end
  end
  
  def self.send_sms!
    find_all_by_sms_spread_status('ready').each do |info|
      if info.sm_content.present?
        info.sms_spreading!
        logger.debug "准备短信推广-#{info.title}"
        User.all_binded_mobile.each do |user|
          Sm.create!( :user => user,
            :content =>  info.sm_content,
            :pri => 1) if user.mobile? 
          info.add_sms_count
        end
        info.sms_spread_done!
      end
    end
  end
  
  def spreaded?
    (sms_count + emails_count) > 0
  end
  
  def add_emails_count
    self.emails_count = emails_count + 1
  end
  
  def add_sms_count
    self.sms_count = sms_count + 1
  end
  
  def add_emails_count!
    add_emails_count
    save(false)
  end
  
  def add_sms_count!
    add_sms_count
    save(false)
  end
  
  def money_purpose
    ActiveSupport::StringInquirer.new(self[:money_purpose])
  end
  
  def emails_spread_status
    ActiveSupport::StringInquirer.new(self[:emails_spread_status])
  end
  
  def sms_spread_status
    ActiveSupport::StringInquirer.new(self[:sms_spread_status])
  end
  
  def emails_spread_ready!
    self.emails_spread_status = 'ready'
    save false
  end
  
  def sms_spread_ready!
    self.sms_spread_status = 'ready'
    save false
  end
  
  def emails_spreading!
    self.emails_spread_status = 'spreading'
    save false
  end
  
  def sms_spreading!
    self.sms_spread_status = 'spreading'
    save false
  end
  
  def give_up_emails_spread!
    self.emails_spread_status = 'done'
    save false
  end
  
  def give_up_sms_spread!
    self.sms_spread_status = 'done'
    save false
  end
  
  def emails_spread_done!
    self.emails_spread_status = 'done'
    self.emailed_at = Time.now
    save false
  end
  
  def sms_spread_done!
    self.sms_spread_status = 'done'
    self.smed_at = Time.now
    save false
  end
  
  def self.capture_weather_alerts!    
    rss_items.each do |item|      
      Info.new(
        :info_type_id => InfoType.find_by_code('weather_alert').id,
        :title => item.title,
        :email_title => item.title,
        :content => item.description.squish,
        :sm_content => item.description.squish,
        :email_content => item.description.squish,
        #:published_at => item.pubDate,
        :url => item.link
      ).create_and_send_sm
    end
  end
  
  def self.rss_items
    rss = RSS::Parser.parse(open("http://www.weather.com.cn/rss/alert.xml").read, false)
    channel = rss.channel       
    items = rss.items # rss.channel.items亦可
  end
  
  def alerted_areas
    @alerted_areas
  end
  
  def alerted_cities
    @alerted_cities
  end
  
  def alerted_provinces
    @alerted_provinces
  end
  
  def self.find_all_by_area_from_rss(area)     
    infos = Info.rss_items.each_with_object([]) do |item,infos|      
      info = Info.new(
        :title => item.title,
        :content => item.description.squish,
        :url => item.link
      ) 
      logger.debug item.pubDate
      infos << info if info.alert?(area.short_name)      
    end
    logger.debug "===================== areas's infos size : #{infos.size}"
    Info.rss_items.each_with_object(infos) do |item,infos|
      info = Info.new(
        :title => item.title,
        :content => item.description,
        :url => item.link
      ) 
      infos << info if info.alert?(area.city.name)      
    end if infos.empty?
    logger.debug "===================== cities's infos size : #{infos.size}"
    Info.rss_items.each_with_object(infos) do |item,infos|
      info = Info.new(
        :title => item.title,
        :content => item.description,
        :url => item.link
      ) 
      infos << info if info.alert?(area.province.name)      
    end if infos.empty?
    infos
  end
  
  def create_and_send_sm    
    if save
      @alerted_areas = []
      @alerted_cities = []
      @alerted_provinces = []
      logger.debug "weather_alert's title : #{title}"
      logger.debug "weather_alert's sm_content : #{sm_content}"
      # 发区域
      logger.debug "================= areas"
      Area.all.each_with_object(@alerted_areas) do |area,@alerted_areas|
        @alerted_areas << area if alert?(area.short_name) 
      end
      if @alerted_areas.empty?
        # 发城市
        logger.debug "================= cities"
        City.all.each_with_object(@alerted_cities) do |city,@alerted_cities|
          @alerted_cities << city if alert?(city.name)
        end  
        if @alerted_cities.empty?
          # 发省份
          logger.debug "================= provinces"
          Province.all.each_with_object(@alerted_provinces) do |province,@alerted_provinces|            
            @alerted_provinces << province if alert?(province.name)
          end
        end
      end
      # 区域
      @alerted_areas.each do |area|
        logger.debug "发送区域-#{area.short_name}的-气象预警"
        UserToolSetting::WeatherForecast.find_all_by_area_id(area.id).each do |setting|
          setting.user.send_weather_alert_sm(self)
          self.sms_count += 1
        end
      end
      # 城市
      @alerted_cities.each do |city|
        logger.debug "发送城市-#{city.name}的-气象预警"
        UserToolSetting::WeatherForecast.all(
          :conditions => ['areas.city_id = ?',city.id],
          :include => :area
        ).each do |setting|
          setting.user.send_weather_alert_sm(self)
          self.sms_count += 1
        end
      end
      # 省份
      @alerted_provinces.each do |province|
        logger.debug "发送省份-#{province.name}的-气象预警"
        UserToolSetting::WeatherForecast.all(
          :conditions => ['areas.province_id = ?',province.id],
          :include => :area
        ).each do |setting|
          setting.user.send_weather_alert_sm(self)
          self.sms_count += 1
        end
      end
      save false
    end
  end
  
  def alert?(area_or_city_or_province_name) 
    logger.debug "#{title} =~ #{area_or_city_or_province_name} is #{title =~ instance_eval("/#{area_or_city_or_province_name}/") or content =~ instance_eval("/#{area_or_city_or_province_name}/")}" 
    title =~ instance_eval("/#{area_or_city_or_province_name}/") or content =~ instance_eval("/#{area_or_city_or_province_name}/")
  end
  
end
